import sys

from PyQt6.QtCharts import QChart, QChartView, QBarSet, QBarSeries, QAbstractBarSeries, QLineSeries, \
    QBarCategoryAxis, QValueAxis
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPen
from PyQt6.QtWidgets import QApplication, QWidget


class MyChart(QWidget):
    def __init__(self):
        super(MyChart, self).__init__()
        self.setWindowTitle('柱状图')

        # 图表
        chart = QChart()
        chart.setTitle('2017-2021年高考人数和录取率')
        chart.legend().setAlignment(Qt.AlignmentFlag.AlignTop)
        chartView = QChartView(self)
        chartView.setGeometry(10, 10, 800, 600)
        chartView.setChart(chart)

        data = [
            # 报考
            [940, 975, 1031, 1071, 1078],
            # 录取
            [700, 791, 820, 967.5, 689]
        ]

        # 柱状图
        signup = QBarSet('报考')
        enroll = QBarSet('录取')
        for i in range(5):
            signup.append(data[0][i])
            enroll.append(data[1][i])

        bSeries = QBarSeries()
        bSeries.append(signup)
        bSeries.append(enroll)
        bSeries.setLabelsVisible(True)
        bSeries.setLabelsPosition(QAbstractBarSeries.LabelsPosition.LabelsInsideEnd)
        chart.addSeries(bSeries)

        # 折线图
        lSeries = QLineSeries()
        lSeries.setName('趋势')
        for i in range(5):
            lSeries.append(i, data[1][i])
        pen = QPen(Qt.GlobalColor.red)
        pen.setWidth(2)
        lSeries.setPen(pen)
        lSeries.setPointLabelsVisible(True)
        lSeries.setPointLabelsFormat('(@yPoint 万)')
        chart.addSeries(lSeries)

        # 坐标轴
        year = ['2017', '2018', '2019', '2020', '2021']
        axisX = QBarCategoryAxis()
        axisX.append(year)
        chart.addAxis(axisX, Qt.AlignmentFlag.AlignBottom)
        bSeries.attachAxis(axisX)
        lSeries.attachAxis(axisX)

        axisY = QValueAxis()
        axisY.setTitleText('人数（万）')
        chart.addAxis(axisY, Qt.AlignmentFlag.AlignLeft)
        bSeries.attachAxis(axisY)
        lSeries.attachAxis(axisY)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MyChart()
    main.show()
    sys.exit(app.exec())
